package com.yht.org.controller;

import com.yht.basic.util.AjaxResult;
import com.yht.basic.util.QueryResult;
import com.yht.org.domain.Employee;
import com.yht.org.query.EmployeeQuery;
import com.yht.org.service.IEmployeeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController//springmvc对restful风格的支持，包含@Controller和@ResponseBody
@RequestMapping("/emp")
@Api(value = "员工的API",description="员工相关的CRUD功能")
public class EmployeeController {
    /*注入*/
    @Autowired
    private IEmployeeService employeeService;

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询" )
    public Employee queryById(@PathVariable @ApiParam(name="ID属性",required = true) Long id){
        return employeeService.findById(id);
    }

    /**
     * 查询所有
     * @return
     */
    @GetMapping
    @ApiOperation(value = "查询所有数据" )
    public List<Employee> queryAll(){
        return employeeService.findAll();
    }
    //@RequestBody从请求体中获取json格式的参数
    //@RequestParam 从请求体或者url路径中获取id=xcx&name=xx格式的参数
    /**
     * 分页查询
     * @param employeeQuery
     * @return
     */
    @PostMapping
    @ApiOperation(value = "分页查询" )
    public QueryResult<Employee> queryPage(@RequestBody EmployeeQuery employeeQuery){
        return employeeService.findByEmployeeQuery(employeeQuery);
    }

    /**
     * 根据id删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据id删除" )
    public AjaxResult deleteById(@PathVariable Long id){
        try {
            employeeService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("删除失败");
        }
    }

    /**
     * 新增或者修改操作
     * @param employee
     * @return
     */
    @PutMapping
    @ApiOperation(value = "新增或者修改操作" )
    public AjaxResult addOrUpdate(@RequestBody Employee employee){
        try {
            if(employee.getId() == null){
                employeeService.add(employee);
            }else{
                employeeService.update(employee);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("保存失败");
        }

    }

    /**
     * 批量删除
     * @return
     */
   /* @PatchMapping
    public AjaxResult batchDelete(@RequestBody List<Long> ids){
        try {
            employeeService.batchDelete(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("删除失败");
        }
    }*/
}
